% file reflect2d_arbline_pre.m
% ENGR 150 exercise
% reflect point around arbitrary line
% 2-D to start
% newpoint = givenpoint * composite transformation T

% =======================================
% MATLAB HELP
% to learn more about Matlab, type 'intro'
% (without quotes) at the command prompt
% also type 'demo' for more complete intro
% for help on any function, type 'helpwin functionname'
% for help on syntax:
% type 'helpwin punct' 'helpwin ops'  'helpwin arith'
% 'helpwin colon'
% for web-based help, type 'helpdesk'
% keyword search, type 'lookfor keyword'
% type variable names to get their values
% =========================================

% inputs: givenpoint (x,y) and
% line defined by 2 endpoints endpt1 endpt2
% output: reflected point

% enter inputs
vertex_matrix=[1 0 ;0 0;0 1 ;2 1 ;2 4 ;3 4 ;5 1 ;10 0 ;
  5 -1 ;3 -4 ;2 -4 ;2 -1 ;0 -1 ;0 0 ;];

givenpoint=-5*ones(14,1)*[1 0]+5*ones(14,1)*[0 1]+vertex_matrix;

v=vertex_matrix';

%patch(v(1,:),v(2,:),'r','AmbientStrength',1,'DiffuseStrength',0.5,...
%    'SpecularStrength',0,'SpecularExponent',5,'SpecularColorReflectance',0,...
%    'FaceLighting','phong','EdgeLighting','phong');
%ka=1;kd=0.5;ks=1;n=5;sc=1;
%material([ka kd ks n sc]);
%lighting phong;


%givenpoint= [4 4]; % = (x,y)
endpt1 = [2 3]; 
endpt2 = [5 8];

% start transformation
% add extra dimension
gpoint = [givenpoint ones(14,1)];

%use endpt1 endpt2 to define line as a matrix
%example: gline = [2 3;
%                  5 6]; 
gline = [endpt1;
        endpt2]; 
% note that we can write
% endpt1 = gline(1,:)
% is row 1 of matrix gline, 
% for practice, type these variable names
% at the command prompt to see their values

% T1: translation of endpt1 to origin
dx=endpt1(1);
dy=endpt1(2);
T1=[ 1  0  0;
     0  1  0;
   -dx -dy 1];
 
 %phi=atan2((6-3),(5-2));
 %phi=atan2(gline(2,2)-gline(1,2),gline(2,1)-gline(1,1));
 % gline(:,2) is column 2 of matrix gline
 % diff(vector) is a vector of differences
 phi=atan2( diff(gline(:,2)),diff(gline(:,1)) );
 
 % T2: rotate line to x-axis
 T2=[cos(-phi) sin(-phi) 0;
    -sin(-phi) cos(-phi) 0;
    0        0        1]; 
 
 % T3: reflect about x-axis
 T3=[ 1 0 0;
      0 -1 0;
      0 0 1]; 
   
 % T4: rotate back  
 T4=[cos(phi) sin(phi) 0;
    -sin(phi) cos(phi) 0;
    0        0        1]; 
 
 % T5: translate back
 T5=[1  0  0;
     0  1  0;
     dx dy 1];
  
 % composite transformation
 Tcomp=T1*T2*T3*T4*T5; 
 
 % compute new point
 npoint=gpoint*Tcomp;  
 
 npoint(:,3)=[]; 
 % eliminate 3rd component of 1x3 vector 
 % using []=empty set
 % thus npoint is now 1x2
 newpoint=npoint; % 1x2 vector
            
 % plot line and points              
 hold on;
 plot(gline(:,1),gline(:,2));             
 plot(givenpoint(:,1),givenpoint(:,2),'r-');              
 plot(npoint(:,1),npoint(:,2),'g-');
 axis equal;
 xlabel('x');ylabel('y');
 title('Reflect point about line');
 hold off;
 
